package com.xiaoyu.client.ui.activity.mall;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.PayResult;
import com.xiaoyu.client.model.goods.GoodsFormatBean;
import com.xiaoyu.client.model.goods.OrderConfirmBean;
import com.xiaoyu.client.model.mine.AddressBean;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.main.mine.my_info.AddressActivity;
import com.xiaoyu.client.ui.activity.main.mine.set_favorable.AvailableFragment;
import com.xiaoyu.client.ui.activity.main.mine.set_favorable.FavorableActivity;
import com.xiaoyu.client.ui.dialog.SpecificationDialog;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivityWithTitle;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.Map;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author jx
 * @date 创建时间 2018/12/6
 * @Description 确认订单
 */
public class OrderComfirmActivity extends BaseActivityWithTitle {

    public static final int ORDER_ADDRESS = 0;
    public static final int ORDER_COUPON = 1;
    public static final String ORDER_MONEY = "order_money";
    private static final int SDK_PAY_FLAG = 1;
    @BindView(R.id.activity_order_comfim_address_txt)
    TextView mAddress;//地址
    @BindView(R.id.order_comfirm_goods_img)
    ImageView goodsImg;//商品图片
    @BindView(R.id.order_comfirm_goods_name)
    TextView goodsName;//商品名称
    @BindView(R.id.order_comfirm_goods_buy_count)
    TextView goodsCount;//商品购买数量
    @BindView(R.id.order_comfirm_goods_price)
    TextView goodsPrice;//商品价格
    @BindView(R.id.order_comfirm_goods_total_price)
    TextView totalPrice;//商品总额
    @BindView(R.id.order_comfirm_goods_coupon_txt)
    TextView couponTxt;//优惠券
    @BindView(R.id.order_comfirm_goods_really_price)
    TextView reallyPrice;//实付款
    @BindView(R.id.order_comfirm_goods_bottom_price)
    TextView bottomPrice;//底部实付款
    @BindView(R.id.order_confirm_store_name)
    TextView mNameAndPhone;//名和手机号
    @BindView(R.id.activity_examine_order_store)
    TextView mStoreNames;
    @BindView(R.id.order_comfirm_goods_freight)
    TextView mFreight;//运费

    private String buyCount;//购买数量
    private String addressId;//地址id
    private double money;//商品总额(为了传值给优惠券选择页)
    private double price;//实付款（为了传值给支付弹窗）(实付款 = 商品总额 - 运费 - 优惠券)
    private GoodsFormatBean.FormatParam formatModel;//商品规格
    private Context mContext;
    private OrderConfirmBean bean;
    private String usercouponsid = "";//优惠卷id

    @Override
    protected void loadContentView(ViewGroup parent) {
        mContext = this;
        setTitleText("确认订单");
        requestPermission();
        LayoutInflater.from(this).inflate(R.layout.activity_order_comfirm, parent, true);
        ButterKnife.bind(this);
        parseIntent();
        getConfirmDetails();
    }

    private void parseIntent() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            formatModel = (GoodsFormatBean.FormatParam) bundle.getSerializable(SpecificationDialog.GOODS_BUY_FORMAT);
            buyCount = bundle.getString(SpecificationDialog.GOODS_BUY_COUNT);

        }
    }

    //选择地址
    @OnClick(R.id.activity_order_comfirm_address)
    public void addressClick() {
        Intent intent = new Intent(this, AddressActivity.class);
        startActivityForResult(intent, ORDER_ADDRESS);
    }

    //选择优惠券
    @OnClick(R.id.order_comfirm_goods_coupon_item)
    public void couponItemClick() {
        Intent intent = new Intent(this, FavorableActivity.class);
        intent.putExtra(ORDER_MONEY, money);
        startActivityForResult(intent, ORDER_COUPON);
    }

    //立即购买
    @OnClick(R.id.order_comfirm_goods_buy_now_btn)
    public void buyNowClick() {
        PayOrderDialog payDialog = new PayOrderDialog(this);
        payDialog.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取选中默认地址
        if (requestCode == ORDER_ADDRESS && resultCode == AddressActivity.RESULT_OK && data != null) {
            mAddress.setText(data.getStringExtra(AddressActivity.ADDRESS_DETAILS));
            addressId = data.getStringExtra(AddressActivity.ADDRESS_ID);
        }
        //获取优惠券
        if (requestCode == ORDER_COUPON && resultCode == FavorableActivity.RESULT_OK && data != null) {
            AddressBean.DataBean couponModel = (AddressBean.DataBean) data.getExtras().getSerializable(AvailableFragment.COUPON_CHOOSE);
            String offer = couponModel.getCouponsmoney();
            //优惠卷id
            usercouponsid = couponModel.getUsercouponsid();
            couponTxt.setText("-" + offer);
            couponTxt.setTextColor(Color.parseColor("#ff0000"));
            price = sub(money, Double.parseDouble(offer));
            if (price <= 0) {
                reallyPrice.setText("¥0");
                bottomPrice.setText("¥0");
            } else {
                reallyPrice.setText("¥" + price);
                bottomPrice.setText("¥" + price);
            }
        }
    }

    //两个Double数相减
    public static Double sub(Double v1, Double v2) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        double result = b1.subtract(b2).doubleValue();
        BigDecimal r = new BigDecimal(result);
        return r.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    private void getConfirmDetails() {
        NetworkManager.getConfirmOrder(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), buyCount,
                formatModel.getGoodsdetailsid(), "", new CommonHttpResponser() {
                    @Override
                    public void onSuccess(String result) {
                        succeedResult(result);
                    }

                    @Override
                    public void onFailed(String errorCode, String errorDiscription) {

                    }
                });

    }

    //解析数据并显示内容
    private void succeedResult(String result) {
        ToastUtil.logResult("订单信息", result);
        bean = new Gson().fromJson(result, OrderConfirmBean.class);
        addressId = bean.getData().getAddress().getAddressid();
        if (bean.getData().getAddress().getReceiver() == null) {
            mNameAndPhone.setText("");//人名和手机号
        } else {
            mNameAndPhone.setText(bean.getData().getAddress().getReceiver() + "  " + bean.getData().getAddress().getTel());//人名和手机号
        }

        if (bean.getData().getAddress().getProvinces() == null) {
            mAddress.setText("请输入信息");//地址
        } else {
            mAddress.setText(bean.getData().getAddress().getProvinces() + bean.getData().getAddress().getCity() +
                    bean.getData().getAddress().getCounty() + bean.getData().getAddress().getDetail());//地址
        }
        mStoreNames.setText(bean.getData().getGoodsstore().getStorename());//商铺名字
        Glide.with(this).load(bean.getData().getGoodsdeimg()).into(goodsImg);//商品图片
        goodsName.setText(bean.getData().getGoodsname());//商品名字
        goodsCount.setText("数量： " + bean.getData().getGoodsnumber());//商品数量
        goodsPrice.setText("¥" + bean.getData().getGoodsprice1());//商品价格
        totalPrice.setText("¥" + bean.getData().getGoodsmoney());//商品总额
        money = Double.parseDouble(bean.getData().getGoodsmoney());
        if (bean.getData().getGoodsfreight().equals("0")) {//邮费
            mFreight.setText("免邮");//邮费
        } else {
            mFreight.setText("运费：¥" + bean.getData().getGoodsfreight());
        }
        couponTxt.setText(bean.getData().getCoupons().getCouponsname());//没有选择优惠券

        price = sub(Double.parseDouble(bean.getData().getGoodsmoney()), Double.parseDouble(bean.getData().getGoodsfreight()));
        reallyPrice.setText("¥" + price);//实付款
        bottomPrice.setText("¥" + price);//底部实付款
    }


    class PayOrderDialog extends Dialog {
        private RadioGroup payGroup;
        private TextView priceTxt;//价格
        private TextView payBtn;//确认支付

        public PayOrderDialog(@NonNull Context context) {
            super(context, R.style.MyDialog);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.dialog_pay_three_way);
            initUI();
            Window window = this.getWindow();
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
        }

        private void initUI() {
            payGroup = findViewById(R.id.dialog_pay_way_btn_group);
            priceTxt = findViewById(R.id.dialog_pay_price);
            payBtn = findViewById(R.id.dialog_pay_btn);

            ((RadioButton) payGroup.getChildAt(0)).setChecked(true);
            priceTxt.setText(price + "");

            //确认支付
            payBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (payGroup.getCheckedRadioButtonId()) {
                        case R.id.dialog_pay_balance_btn://余额支付
                            ToastUtil.showToast(OrderComfirmActivity.this, "支付成功");
                            commitOrder("wallet");
                            break;
                        case R.id.dialog_pay_alipay_btn://支付宝支付
                            commitOrder("ali");
                            break;
                        case R.id.dialog_pay_wechat_btn://微信支付
                            commitOrder("wx");
                            break;
                    }
                }
            });

            payGroup.setOnCheckedChangeListener(onCheckedChangeListener);
        }

        private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.dialog_pay_balance_btn://余额支付
                        ((RadioButton) payGroup.getChildAt(0)).setChecked(true);
                        break;
                    case R.id.dialog_pay_alipay_btn://支付宝支付
                        ((RadioButton) payGroup.getChildAt(1)).setChecked(true);
                        break;
                    case R.id.dialog_pay_wechat_btn://微信支付
                        ((RadioButton) payGroup.getChildAt(2)).setChecked(true);
                        break;
                }
            }
        };
    }

    /**
     * 提交订单
     */
    private void commitOrder(final String payWay) {
        NetworkManager.toCommitOrder(payWay, formatModel.getGoodsdetailsid(), bean.getData().getGoodsnumber(),
                usercouponsid, addressId, new CommonHttpResponser() {
                    @Override
                    public void onSuccess(String result) {
                        String orderInfo = null;
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            orderInfo = jsonObject.getString("data");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (payWay.equals("wallet")) {//余额支付
                            finish();
                            return;
                        }
                        if (payWay.equals("wx")) {//微信支付
                            ToastUtil.logResult("暂未开放", result);
                        }
                        if (payWay.equals("ali")) {//支付宝支付
                            toAliPay(orderInfo);
                        }
                    }

                    @Override
                    public void onFailed(String errorCode, String errorDiscription) {
                        ToastUtil.showToast(OrderComfirmActivity.this, "支付失败");
                    }
                });
    }


    /**
     * 支付(支付宝)
     */
    private void toAliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderComfirmActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus，为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        ToastUtil.showToast(OrderComfirmActivity.this, "支付成功");
                        finish();
                    } else {
                        //该笔订单真实的支付结果，需要依赖服务端的异步通知
                        ToastUtil.showToast(OrderComfirmActivity.this, "支付失败");
                        finish();
                    }
            }
        }
    };


    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, 123);

        }
    }

    /**
     * 权限获取回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 123: {

                // 用户取消了权限弹窗
                if (grantResults.length == 0) {

                    return;
                }

                // 用户拒绝了某些权限
                for (int x : grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        return;
                    }
                }

                // 所需的权限均正常获取
            }
        }
    }

}
